<template>
  <div>
    <div class="box">
      <div class="left">
        <div class="first">
          <span>车位名:</span>
          <el-input
            v-model="input"
            placeholder="请输入车位名"
            style="margin-top: 5px"
          ></el-input>
        </div>
        <div class="first">
          <span>车位金额:</span>
          <el-input
            v-model="input1"
            placeholder="请输入车位金额"
            style="margin-top: 5px"
          ></el-input>
        </div>
        <div class="first">
          <span>车位类型:</span>
          <el-select
            v-model="input2"
            placeholder="请选择车位类型"
            style="display: block; margin-top: 5px"
            clearable
          >
            <el-option label="地下" value="1"></el-option>
            <el-option label="地上" value="2"></el-option>
          </el-select>
        </div>
        <div class="first">
          <span>车位状态:</span>
          <el-select
            v-model="input3"
            placeholder="请选择车位状态"
            style="display: block; margin-top: 5px"
            clearable
          >
            <el-option label="已有车" value="1"></el-option>
            <el-option label="未有车" value="2"></el-option>
          </el-select>
        </div>
        <div class="anniu">
          <el-button
            type="primary"
            icon="el-icon-search"
            style="width: 150px"
            @click="search"
            >查询</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-edit"
            style="width: 150px"
            @click="back"
            >重置</el-button
          >
        </div>
      </div>
      <div class="right">
        <div class="head">
          <h2>车位列表</h2>
          <el-button
            type="success"
            icon="el-icon-plus"
            style="width: 100px; float: right"
            @click="add"
            >新增</el-button
          >
        </div>
        <el-table
          :data="tableData"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
          @sort-change="handleSortChange"
        >
          <el-table-column
            prop="address"
            label="序号"
            :formatter="formatter"
            width="100"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="parkname"
            label="车位名称"
            sortable
            width="150"
          >
          </el-table-column>
          <el-table-column prop="parkpay" label="车位金额" sortable width="180">
          </el-table-column>
          <el-table-column label="车位类型" :formatter="formatter" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.parktype"
                active-text="地下"
                inactive-text="地上"
                :active-value="1"
                :inactive-value="2"
                @change="handleStatusChange(scope.row, $event)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="车位状态" :formatter="formatter" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.parkstatus"
                active-text="已有车"
                inactive-text="未有车"
                :active-value="1"
                :inactive-value="2"
                @change="handleStatusChange1(scope.row, $event)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" :formatter="formatter">
            <template slot-scope="scope">
              <el-button icon="el-icon-share" @click="fenpei(scope.row)" :disabled="scope.row.parkstatus === 1"
                >分配车位</el-button
              >
              <el-button
                icon="el-icon-edit"
                style="color: #62a8ea"
                @click="bianji(scope.row)"
                >编辑</el-button
              >
              <el-button
                icon="el-icon-delete"
                style="border-color: red"
                @click="delete1(scope.row)"
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog title="车位修改" :visible.sync="dialogFormVisible">
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item
          label="车位名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="车位金额"
          :label-width="formLabelWidth"
          prop="region"
        >
          <el-input v-model="form.region" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="车位类型"
          :label-width="formLabelWidth"
          prop="date1"
        >
          <el-select v-model="form.date1" clearable placeholder="请选择">
            <el-option label="地下" :value="1"></el-option>
            <el-option label="地上" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="车位状态"
          :label-width="formLabelWidth"
          prop="date2"
        >
          <el-select v-model="form.date2" clearable placeholder="请选择">
            <el-option label="已有车" :value="1"></el-option>
            <el-option label="未有车" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="keep">保 存</el-button>
        <el-button type="primary" @click="reset">重 置</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增车位" :visible.sync="dialogFormVisible1">
      <el-form ref="ruleForm" :model="formlist" :rules="rules">
        <el-form-item
          label="车位名称"
          :label-width="formLabelWidth"
          prop="first"
        >
          <el-input v-model="formlist.first" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="车位金额"
          :label-width="formLabelWidth"
          prop="second"
        >
          <el-input v-model="formlist.second" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="车位类型"
          :label-width="formLabelWidth"
          prop="third"
        >
          <el-select v-model="formlist.third" clearable placeholder="请选择">
            <el-option label="地下" :value="1"></el-option>
            <el-option label="地上" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="车位状态"
          :label-width="formLabelWidth"
          prop="fourth"
        >
          <el-select v-model="formlist.fourth" clearable placeholder="请选择">
            <el-option label="已有车" :value="1"></el-option>
            <el-option label="未有车" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="keep1">保 存</el-button>
        <el-button type="primary" @click="reset1">重 置</el-button>
      </div>
    </el-dialog>
    <div>
      <!-- 遮罩层（可选） -->
      <div v-if="showTable" class="mask" @click="showTable = false"></div>

      <!-- 自定义弹出层 -->
      <div class="slide-panel" v-if="showTable">
        <div class="panel-header">
          <h2>车位分配</h2>
          <el-button
            icon="el-icon-close"
            @click="showTable = false"
          ></el-button>
        </div>
        <div class="panel-body">
          <el-table
            ref="multipleTable"
            :data="tableData1"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="序号" width="80">
              <template slot-scope="scope">{{ scope.$index+1 }}</template>
            </el-table-column>
            <el-table-column prop="nickname" label="用户账号" width="120">
            </el-table-column>
            <el-table-column prop="homeaddress" label="家庭住址" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="type" label="类型" show-overflow-tooltip>
              <template slot-scope="scope">
              {{scope.row.type === "1"? "管理员" : "普通用户"}}
            </template>
            </el-table-column>
            <el-table-column prop="parkname" label="车位" show-overflow-tooltip>
            </el-table-column>
          </el-table>
          <div class="block">
          <el-pagination
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
            :current-page="current1"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="page1"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
          >
          </el-pagination>
        </div>
        <div class="btn">
        <el-button style="width:200px" @click="showTable = false">取消</el-button>
        <el-button type="primary" style="width:200px" @click="sure">确定</el-button>
        </div>
        </div>
        
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      selectedUserId:"",
      parkname:"",
      parkstatus:"",
      u_id:"",
      current1:1,
      page1:10,
      total1:0,
      showTable: false,
      tableData1: [],

      sortProp: "",
      sortOrder: "",
      id: "",
      dialogFormVisible: false,
      dialogFormVisible1: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formlist: {
        first: "",
        second: "",
        third: "",
        fourth: "",
      },
      formLabelWidth: "120px",
      value1: true,
      value2: true,
      input: "",
      input1: "",
      input2: "",
      input3: "",
      tableData: [],
      current: 1,
      page: 10,
      total: 0,
      rules: {
        name: [
          { required: true, message: "车位名称不能为空", trigger: "blur" },
        ],
        region: [
          { required: true, message: "车位金额不能为空", trigger: "blur" },
        ],
        date1: [
          { required: true, message: "车位类型不能为空", trigger: "change" },
        ],
        first: [
          { required: true, message: "车位名称不能为空", trigger: "blur" },
        ],
        second: [
          { required: true, message: "车位名称不能为空", trigger: "blur" },
        ],
        third: [
          { required: true, message: "车位名称不能为空", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    // 监听显示状态，添加/移除动画类
    showTable(val) {
      this.$nextTick(() => {
        const panel = document.querySelector(".slide-panel");
        if (panel) {
          // 先判断元素是否存在
          if (val) {
            panel.classList.add("show");
          } else {
            panel.classList.remove("show");
          }
        }
      });
    },
  },
  methods: {
    handleSizeChange1(val) {
      console.log(`每页 ${val} 条`);
      this.page1 = val;
      this.current1 = 1;
      this.indexlist1();
    },
    handleCurrentChange1(val) {
      console.log(`当前页: ${val}`);
      this.current1 = val;
      this.indexlist1();
    },
    toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
    
    handleSortChange({ prop, order }) {
      this.sortProp = prop;
      this.sortOrder = order;
      this.current = 1;
      this.indexlist();
    },
    formatter(row, column) {
      return row.address;
    },
    async indexlist() {
      const sortDirection =
        this.sortOrder === "ascending"
          ? "asc"
          : this.sortOrder === "descending"
          ? "desc"
          : "";
      let res = await this.$axios.get(
        `http://community.byesame.com/parking/getParkData?parkname=&parkpay=&parktype=&parkstatus=&currPage=${
          this.current - 1
        }&pageNum=${this.page}&sortProp=${
          this.sortProp
        }&sortOrder=${sortDirection}`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    async indexlist1(){
      let res =  await this.$axios.get(`http://community.byesame.com/users/getUsersData?currPage=${this.current1-1}&pageNum=${this.page1}`)
      console.log(res);
      this.tableData1 = res.data.data
      this.total1 = res.data.total
      console.log(this.tableData1.id);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = val;
      this.current = 1;
      this.indexlist();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.indexlist();
    },
    async handleStatusChange(row, newStatus) {
      const oldStatus = newStatus === 1 ? 2 : 1;
      try {
        const res = await this.$axios.post(
          "http://community.byesame.com/parking/editParkData",
          {
            u_id: row.id,
            parkname: row.parkname,
            parkpay: row.parkpay,
            parktype: row.parktype,
            parkstatus: row.parkstatus,
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
          }
        );
        console.log(res);
        this.$message({ type: "success", message: "更新状态成功!" });
      } catch (error) {
        row.parktype = oldStatus;
        if (error.name === "Cancel") {
          this.$message({ type: "info", message: "已取消更新" });
        } else {
          this.$message({ type: "error", message: "更新失败，请重试" });
        }
      }
    },
    async handleStatusChange1(row, newStatus) {
      const oldStatus = newStatus === 1 ? 2 : 1;
      try {
        const res = await this.$axios.post(
          "http://community.byesame.com/parking/editParkData",
          {
            u_id: row.id,
            parkname: row.parkname,
            parkpay: row.parkpay,
            parktype: row.parktype,
            parkstatus: row.parkstatus,
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
          }
        );
        console.log(res);
        this.$message({ type: "success", message: "更新状态成功!" });
      } catch (error) {
        row.parkstatus = oldStatus;
        if (error.name === "Cancel") {
          this.$message({ type: "info", message: "已取消更新" });
        } else {
          this.$message({ type: "error", message: "更新失败，请重试" });
        }
      }
    },
    reset() {
      this.form.name = "";
      this.form.region = "";
      this.form.date1 = "";
      this.form.date2 = "";
    },
    reset1() {
      this.formlist.name = "";
      this.formlist.region = "";
      this.formlist.date1 = "";
      this.formlist.date2 = "";
    },
    bianji(row) {
      this.dialogFormVisible = true;
      this.form.name = row.parkname;
      this.form.region = row.parkpay;
      this.form.date1 = row.parktype;
      this.form.date2 = row.parkstatus;
      this.id = row.id;
    },
    async keep() {
      let res = await this.$axios.post(
        "http://community.byesame.com/parking/editParkData",
        {
          u_id: this.id,
          parkname: this.form.name,
          parkpay: this.form.region,
          parktype: this.form.date1,
          parkstatus: this.form.date2,
          token:
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
        }
      );
      console.log(res);
      this.$message({ type: "success", message: "车位修改成功!" });
      this.dialogFormVisible = false;
      this.indexlist();
    },
    async keep1() {
      let res = await this.$axios.post(
        "http://community.byesame.com/parking/addParkData",
        {
          parkname: this.formlist.first,
          parkpay: this.formlist.second,
          parktype: this.formlist.third,
          parkstatus: this.formlist.fourth,
          token:
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
        }
      );
      console.log(res);

      this.dialogFormVisible1 = false;
      this.indexlist();
    },
    fenpei(row){
      this.u_id = row.id
      this.parkstatus = row.parkstatus
      this.parkname = row.parkname
      this.showTable = true
    },
     sure(){
      
      this.$confirm("确定分配该车位？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }) .then(async () => {
      try {
      // 2. 调用修改接口，将车位状态改为“已有车”（parkstatus: 1）
      const res = await this.$axios.post(
        "http://community.byesame.com/parking/editParkData",
        {
          u_id: this.u_id, // 当前车位的ID（在fenpei方法中已保存）
          parkname: this.parkname, // 车位名称（保持不变）
          parkpay: this.tableData.find(item => item.id === this.u_id)?.parkpay || '', // 车位金额（从原数据获取）
          parktype: this.tableData.find(item => item.id === this.u_id)?.parktype || 1, // 车位类型（保持不变）
          parkstatus: 1, // 改为“已有车”
          userId: this.selectedUserId, // 关联选中的用户ID（根据接口字段调整）
          token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
        }
      );

      // 3. 处理成功响应
      console.log("分配成功", res);
      this.$message({ type: "success", message: "分配车位成功!" });
      this.showTable = false; // 关闭弹框
      this.indexlist(); // 刷新车位列表
      this.$refs.multipleTable.clearSelection(); // 清空选择
      this.selectedUserId = null; // 重置选中的用户ID
    } catch (error) {
      // 4. 处理失败情况
      console.error("分配失败", error);
      this.$message({ type: "error", message: "分配失败，请重试" });
    }
  }).catch(() => {
    this.$message({ type: "info", message: "已取消分配" });
  });
    },
    delete1(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios.get(
            `http://community.byesame.com/parking/delParkData?id=${row.id}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA`
          );
          console.log(res);

          this.indexlist();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    add() {
      this.dialogFormVisible1 = true;
      this.formlist.date2 = "未有车";
    },
    back() {
      this.input = "";
      this.input1 = "";
      this.input2 = "";
      this.input3 = "";
      this.sortProp = "";
      this.sortOrder = "";
      this.indexlist();
    },
    async search() {
      const sortDirection = 
    this.sortOrder === "ascending" 
      ? "asc" 
      : this.sortOrder === "descending" 
        ? "desc" 
        : "";
      let res = await this.$axios.get(
        `http://community.byesame.com/parking/getParkData?parkname=${
          this.input
        }&parkpay=${this.input1}&parktype=${this.input2}&parkstatus=${
          this.input3
        }&currPage=${this.current - 1}&pageNum=${this.page}&sortProp=${
          this.sortProp
        }&sortOrder=${sortDirection}`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
  },
  created() {
    this.sortProp = "parkpay";
    this.sortOrder = "descending";
    this.indexlist();
    this.indexlist1();
  },
};
</script>
<style scoped>
.btn{
  width: 70%;
  margin: 0 auto;
  margin-top: 20px;
  display: flex;
  justify-content: space-around;
}
.box {
  width: 99%;

  display: flex;
}
.left {
  width: 30%;
}
.right {
  width: 68%;

  margin-left: 20px;
}
.first {
  margin-top: 30px;
}
.first span {
  color: #777;
  font-size: 14px;
}
.anniu {
  width: 100%;
  text-align: center;
  margin-top: 30px;
}
.head {
  width: 100%;
}
.head h2 {
  float: left;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

/* 左侧弹出层 */
.slide-panel {
  position: fixed;
  top: 0;
  left: 0;
  width: 800px;
  height: 100vh;
  background: #fff;
  z-index: 1001;
  transform: translateX(-100%); /* 初始位置：左侧外部 */
  transition: transform 0.3s ease-out;
}

/* 显示时的位置 */
.slide-panel.show {
  transform: translateX(0); /* 滑入可视区域 */
}

/* 头部样式 */
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

/* 表格容器样式 */
.panel-body {
  padding: 20px;
  height: calc(100% - 60px); /* 减去头部高度 */
  overflow: auto; /* 内容超出时滚动 */
}
</style>